package com.fingard.dsp.bank.directbank.nccb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class NCCB01Transaction extends NCCB01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            NCCB01Header header = new NCCB01Header();
            header.transCode = "eacqry.AcTrsQry.do";
            header.serialNo = p_req7516.reqHeader.transSeqID;
            header.msgType = "0";
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());
            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            String recordNumber = "0";
            while (tmpIntDateFrom <= tmpIntDateTo && StringHelper.isNullOrEmpty(tmpRespCode)) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                int tmpPageNumber = 0;//页码数，默认查询第一页
                int tmpNowReadedCount = 0;//已读条数
                //int tmpPageShowNum = 5;//每页显示记录数
                boolean tmpQryNext = true;
                Map<String, Integer> tmpTotalNum = new HashMap<String, Integer>();
                while (tmpNowReadedCount == 0 || tmpNowReadedCount < tmpTotalNum.get("totalCount")) {//分页查询
                    XmlTextWriter xmlWriter = new XmlTextWriter();//发送银行报文的XML对象
                    //写入通用的头部节点
                    writeCommonHeader(xmlWriter, header);
                    xmlWriter.writeStartElement("Body");
                    xmlWriter.writeElementString("AcNo", p_req7516.actNum);
                    xmlWriter.writeElementString("SubAcNo",""); //子账户
                    String tmpCur = convertCurToATS(p_req7516.actCur);
                    xmlWriter.writeElementString("Currency",tmpCur); //币种
                    xmlWriter.writeElementString("BeginDate", Format.Date8Format.format(tmpCalendarFrom.getTime()));
                    xmlWriter.writeElementString("EndDate", Format.Date8Format.format(tmpClndrStepTo.getTime()));

                    xmlWriter.writeElementString("QryDir","A");
                    xmlWriter.writeElementString("QHTranstype","");
                    xmlWriter.writeElementString("currentIndex", String.valueOf(tmpPageNumber));
                    xmlWriter.writeElementString("pageSize", getBankConfig().getValueAsString("pageSize"));
                    xmlWriter.writeElementString("recordNumber",recordNumber);

                    xmlWriter.writeEndDocument();
                    String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(),header);
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                        if (tmpBkReader != null) {
                            String tmpRetCode = tmpBkReader.getFirstText("/Message/Head/RejCode");
                            String respondInfo = tmpBkReader.getFirstText("/Message/Head/RejMsg");
                            if(tmpRetCode.equals("FIN0000")) {
                                recordNumber = tmpBkReader.getFirstText("/Message/Body/recordNumber");
                                if (StringHelper.hasAnyChar(recordNumber)) {
                                    if (tmpTotalNum.containsKey("totalCount")) {
                                        if (tmpTotalNum.get("totalCount").intValue() != Integer.valueOf(recordNumber).intValue()) {
                                            tmpRespCode = "-1";
                                            tmpRespInfo = "相同条件前后查出来的总数不一致";
                                            break;
                                        }
                                    } else {
                                        if ("0".equals(recordNumber)) {
                                            break;
                                        }
                                        tmpTotalNum.put("totalCount", Integer.valueOf(recordNumber));
                                    }
                                    while (tmpBkReader.read("/Message/Body/List/Record")) {
                                        ++tmpNowReadedCount;
                                        RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                        tmpRetDetail.actNum = p_req7516.actNum;
                                        tmpRetDetail.recAccNum = tmpBkReader.readedXElement.getSingleText("YourRichNbr");
                                        tmpRetDetail.recAccName = tmpBkReader.readedXElement.getSingleText("YourRichName");
                                        //tmpRetDetail.recAccBank = "";
                                        String tmpTranDate = tmpBkReader.readedXElement.getSingleText("AcctDate");
                                        if(tmpTranDate.length()==8 ){
                                            tmpTranDate = tmpTranDate.substring(0,4) + "-" + tmpTranDate.substring(4,6) + "-" + tmpTranDate.substring(6,8);
                                        }
                                        tmpRetDetail.tranDate = tmpTranDate;
                                        String tmpTranTime = tmpTranDate + " 00:00:00";
                                        tmpRetDetail.tranTime = tmpTranTime;
                                        tmpRetDetail.valueDate = tmpTranDate;//起息日没有返回就用交易日
                                        tmpRetDetail.accBal = tmpBkReader.readedXElement.getSingleText("Balance");
                                        tmpRetDetail.askNumber = tmpBkReader.readedXElement.getSingleText("TransNbr");
                                        String tmpTranAmt = tmpBkReader.readedXElement.getSingleText("Amount").replace("-","");
                                        String creditDebitFlag = tmpBkReader.readedXElement.getSingleText("TransDir");
                                        if (creditDebitFlag != null) {
                                            if (creditDebitFlag.equals("D")) //借贷标识
                                            {

                                                    tmpRetDetail.cdFlag = "1";

                                            } else {

                                                    tmpRetDetail.cdFlag = "2";
                                            }
                                        }
                                        tmpRetDetail.tranAmt = tmpTranAmt;
                                        tmpRetDetail.comment = tmpBkReader.readedXElement.getSingleText("Reserve80");
                                        tmpRetDetail.cur = p_req7516.actCur;
                                        retAts.writeRetDetail(tmpRetDetail);
                                        ++tmpPageNumber;

                                    }

                                } else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "turnPageTotalNum为空";
                                    break;
                                }
                            }else{
                                tmpRespCode = "-1";
                                tmpRespInfo = tmpRetCode + ":" + respondInfo;
                                break;
                            }

                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                            break;
                        }
                    }else {
                        tmpRespCode = "-1";
                        tmpRespInfo = "请求失败";
                        break;
                    }
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if ("-1".equals(tmpRespCode)) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }
}
